<template>
  <div class="dropdown-select" :class="[size, { disabled, readonly }]">
    <!-- 触发区域 -->
    <div
        class="select-trigger"
        :style="inputStyle"
        @click="toggleDropdown"
        @keydown="handleTriggerKeydown"
        tabindex="0"
    >
      <slot name="trigger" :selected="selectedValue">
        <div class="selected-display">
          <template v-if="multiple">
            <span
                v-for="(item, index) in selectedItems"
                :key="index"
                class="selected-tag"
            >
              {{ getOptionLabel(item) }}
              <span
                  v-if="!disabled && !readonly"
                  class="remove-tag"
                  @click.stop="removeTag(item)"
              >×</span>
            </span>
            <span v-if="!selectedItems.length" class="placeholder">
              {{ placeholder }}
            </span>
          </template>
          <template v-else>
            {{ selectedLabel || placeholder }}
          </template>
        </div>
        <div class="dropdown-indicator">▾</div>
      </slot>
    </div>

    <!-- 下拉菜单 -->
    <teleport to="body">
      <transition name="dropdown">
        <div
            v-show="isOpen"
            class="dropdown-menu"
            :style="dropdownStyle"
            @click.stop
        >
          <!-- 过滤输入框 -->
          <input
              v-if="filterable"
              v-model="filterText"
              class="filter-input"
              :placeholder="filterPlaceholder"
              @input="handleFilterInput"
          />

          <!-- 选项列表 -->
          <div class="options-list" ref="listRef">
            <template v-for="(option, index) in filteredOptions" :key="index">
              <!-- 分组处理 -->
              <div
                  v-if="option.group"
                  class="option-group"
              >
                <slot name="group" :group="option">
                  <div class="group-label">{{ option.group }}</div>
                </slot>
                <div
                    v-for="(item, i) in option.items"
                    :key="i"
                    class="option-item"
                    :class="{
                    selected: isSelected(item),
                    disabled: item.disabled
                  }"
                    @click="selectOption(item)"
                >
                  <slot name="option" :option="item">
                    {{ getOptionLabel(item) }}
                  </slot>
                </div>
              </div>
              <!-- 普通选项 -->
              <div
                  v-else
                  class="option-item"
                  :class="{
                  selected: isSelected(option),
                  disabled: option.disabled
                }"
                  @click="selectOption(option)"
              >
                <slot name="option" :option="option">
                  {{ getOptionLabel(option) }}
                </slot>
              </div>
            </template>
          </div>
        </div>
      </transition>
    </teleport>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  modelValue: [String, Number, Array, Object],
  options: {
    type: Array,
    default: () => []
  },
  optionLabel: {
    type: String,
    default: 'label'
  },
  optionValue: {
    type: String,
    default: 'value'
  },
  placeholder: String,
  disabled: Boolean,
  readonly: Boolean,
  size: {
    type: String,
    validator: v => ['small', 'medium', 'large'].includes(v),
    default: 'medium'
  },
  multiple: Boolean,
  maxSelected: Number,
  dropdownStyle: [Object, String],
  inputStyle: [Object, String],
  filterable: Boolean,
  filterPlaceholder: String
})

const emit = defineEmits([
  'update:modelValue',
  'change',
  'open',
  'close',
  'filter'
])

const isOpen = ref(false)
const filterText = ref('')
const listRef = ref(null)

// 计算选中项
const selectedValue = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

// 处理选项显示标签
const getOptionLabel = option => {
  if (typeof option === 'object') {
    return option[props.optionLabel] || option.label || option.value
  }
  return option
}

// 处理选项实际值
const getOptionValue = option => {
  if (typeof option === 'object') {
    return option[props.optionValue] || option.value
  }
  return option
}

// 当前选中的选项对象
const selectedItems = computed(() => {
  if (!selectedValue.value) return []
  if (props.multiple) {
    return props.options.filter(opt =>
        selectedValue.value.includes(getOptionValue(opt))
    )
  }
  return props.options.find(opt =>
      getOptionValue(opt) === selectedValue.value
  )
})

// 当前显示标签（单选时）
const selectedLabel = computed(() => {
  if (props.multiple) return ''
  return selectedItems.value ? getOptionLabel(selectedItems.value) : ''
})

// 过滤后的选项
const filteredOptions = computed(() => {
  if (!props.filterable || !filterText.value) return props.options
  return props.options.filter(option => {
    const label = getOptionLabel(option).toLowerCase()
    return label.includes(filterText.value.toLowerCase())
  })
})

// 判断选项是否被选中
const isSelected = option => {
  if (props.multiple) {
    return selectedValue.value.includes(getOptionValue(option))
  }
  return getOptionValue(option) === selectedValue.value
}

// 切换下拉框
const toggleDropdown = () => {
  if (props.disabled || props.readonly) return
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    emit('open')
  } else {
    emit('close')
  }
}

// 选择选项
const selectOption = option => {
  if (option.disabled) return

  const value = getOptionValue(option)

  if (props.multiple) {
    const current = Array.isArray(selectedValue.value)
        ? selectedValue.value
        : []
    const index = current.indexOf(value)

    if (index > -1) {
      current.splice(index, 1)
    } else {
      if (props.maxSelected && current.length >= props.maxSelected) return
      current.push(value)
    }
    selectedValue.value = [...current]
  } else {
    selectedValue.value = value
    isOpen.value = false
  }

  emit('change', selectedValue.value)
}

// 移除标签（多选时）
const removeTag = item => {
  if (props.disabled || props.readonly) return
  const value = getOptionValue(item)
  selectedValue.value = selectedValue.value.filter(v => v !== value)
}

// 处理过滤输入
const handleFilterInput = e => {
  emit('filter', e.target.value)
}

// 处理键盘事件
const handleTriggerKeydown = e => {
  if (props.disabled || props.readonly) return

  switch(e.key) {
    case 'ArrowDown':
    case 'Enter':
      isOpen.value = true
      e.preventDefault()
      break
    case 'Escape':
      isOpen.value = false
      break
  }
}

// 点击外部关闭
const clickOutsideHandler = e => {
  if (!isOpen.value) return
  if (!e.target.closest('.dropdown-select')) {
    isOpen.value = false
    emit('close')
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('click', clickOutsideHandler)
})

onUnmounted(() => {
  document.removeEventListener('click', clickOutsideHandler)
})
</script>

<style scoped>
/* 这里需要添加详细的样式代码 */
.dropdown-select {
  position: relative;
  width: 100%;
  max-width: 300px;
}
.select-trigger {
  border: 1px solid #ccc;
  padding: 8px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dropdown-menu {
  position: absolute;
  border: 1px solid #ccc;
  background: white;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
}
.option-item {
  padding: 8px;
  cursor: pointer;
}
.option-item:hover {
  background: #f0f0f0;
}
.selected {
  background: #e0f0ff;
}
.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>